// import { legacy_createStore as createStore } from 'redux'
import { 
  configureStore, // 用于创建仓库
  createAction, // 动态生成 action
  createReducer, // 创建 reducer 处理器函数
 } from './@reduxjs/toolkit'
import logger from 'redux-logger'

const add = createAction('ADD') // 获取一个 add 函数 可以返回 动作类型是 "ADD" 的 action 动作对象
const minus = createAction('MINUS', (payload) => { // 动态生成 payload
  return {
    payload: payload * 2 // 传递的参数 * 2 
  }
})


// function reducer(state = { number: 0 }, action) {
//   switch (action.type) {
//     case add.type: {
//       return { number: state.number + 1 }
//     }
//     case minus.type: {
//       return { number: state.number - action.payload  }
//     }
//     default: {
//       return state
//     }
//   }
// }

const reducer = createReducer({number: 0}, {
  [add]: (state, action) => {
    return {number: state.number + 1}
  },
  [minus]: (state, action) => {
    return {number: state.number - action.payload}
  }
})

// const store = createStore(reducer)
const store = configureStore({
  reducer, // 配置 reducer 处理器函数
  middleware: defaultMiddlewares => [...defaultMiddlewares(), logger], // 合并内置中间件
  preloadedState: { number: 5 },
})

let valueEl = document.getElementById('value')

function render() {
  valueEl.innerHTML = store.getState().number
}

render()

store.subscribe(render)

document.getElementById('add').addEventListener('click', () => store.dispatch(add()))

document.getElementById('minus').addEventListener('click', () => store.dispatch(minus(2)))

// 有内置的 redux-thunk 中间件 dispatch 可以接收一个函数作为参数
document.getElementById('asyncAdd').addEventListener('click', () => store.dispatch((dispatch) => {
  setTimeout(() => {
    dispatch(add())
  }, 1000)
}))
